package com.example.test;

public class OddEvenPrinter {
    private int count = 1;
    private final Object lock = new Object();

    public void printOddEven() {
        /**
         * 打印奇数
         */
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                while (count <= 100) {
                    if (count % 2 == 1) {
                        System.out.println("奇数线程：" + count++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

        /**
         * 打印偶数
         */
        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                while (count <= 100) {
                    if (count % 2 == 0) {
                        System.out.println("偶数线程：" + count++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();
    }

    public static void main(String[] args) {
        OddEvenPrinter printer = new OddEvenPrinter();
        printer.printOddEven();
    }
}
